package com.yongz.controller;

import com.alibaba.fastjson.JSONObject;
import com.yongz.domain.User;
import com.yongz.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    private JSONObject createResponse(int code, String message) {
        JSONObject response = new JSONObject();
        response.put("code", code);
        response.put("msg", message);
        return response;
    }

    private boolean isUserValid(User user) {
        return user.getName() != null && user.getAge() > 0 && user.getEmail() != null && user.getAddress() != null;
    }

    /**
     * 获取用户列表
     *
     * @return
     */
    @GetMapping("/users")
    public List<User> getUsers() {
        return userService.list();
    }

    /**
     * 添加用户
     *
     * @param user
     * @return
     */
    @PostMapping("/addUser")
    public Map addUser(@RequestBody User user) {
        if (!isUserValid(user)) {
            log.error("非法操作,请传入正确的参数");
            return createResponse(403, "非法操作,请传入正确的参数");
        }

        List<User> list = userService.list();
        for (User existingUser : list) {
            if (existingUser.getEmail().equalsIgnoreCase(user.getEmail())) {
                log.error("非法操作,邮箱已存在");
                return createResponse(403, "非法操作,邮箱已存在");
            }
        }

        boolean isSuccess = userService.save(user);
        return createResponse(isSuccess ? 200 : 201, isSuccess ? "数据添加成功" : "未知错误,数据添加失败");
    }

    /**
     * 根据id删除用户
     *
     * @param id
     * @return
     */
    @DeleteMapping("/deleteUserById")
    public Map deleteUserById(Integer id) {
        if (id == null || id == 0) {
            return createResponse(403, "非法操作,请传入正确的参数");
        }

        boolean isSuccess = userService.removeById(id);
        return createResponse(isSuccess ? 200 : 201, isSuccess ? "数据删除成功" : "未知错误,数据删除失败");
    }

    /**
     * 根据id更新用户
     *
     * @param user
     * @return
     */
    @PatchMapping("/updateUserById")
    public Map updateUserById(@RequestBody User user) {
        if (!isUserValid(user)) {
            return createResponse(403, "非法操作,请传入正确的参数");
        }

        boolean isSuccess = userService.updateById(user);
        return createResponse(isSuccess ? 200 : 201, isSuccess ? "数据更新成功" : "未知错误,数据更新失败");
    }


}